//
//  MeatMapViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/8/1.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#define mBottomerH 220.f
#define ZOOM_LEVEL 14


#import "MeatMapViewController.h"
#import "MeatMapShopAddressViewController.h"
#import "MeaetCityFriendHeader.h"
#import "MeatMapBottomer.h"

#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "MKMapView+ZoomLevel.h"


@interface MeatMapViewController ()<CLLocationManagerDelegate, MKMapViewDelegate, AMapSearchDelegate>

@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *useLocation; //当前地址
@property (nonatomic, strong) UIImageView *bigPin; //大头针
@property (nonatomic, strong) UIButton *resetPositionIcon; //重新定位Icon

@property (nonatomic, strong) MeaetCityFriendHeader *bottomer_heaerView;
@property (nonatomic, strong) MeatMapBottomer *bottomer;
@property (strong, nonatomic) UIButton *leftNavBtn;

@property (nonatomic, assign) BOOL isUpdateLocation; //是否更新位置
@property (nonatomic, assign) BOOL isFristPositioning; //是否是第一次定位
@property (nonatomic, assign) BOOL isChooseUpdateLocation; //是否选择更新位置
@property (nonatomic, strong) AMapPOI *fristMapPOI; //定位地址数据
@property (nonatomic, strong) UIView *greenCircle;

@end

@implementation MeatMapViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setupUI];
    [self setupLayout];
}


- (void)setupUI{
    
    self.isFristPositioning = YES;
    self.isChooseUpdateLocation = YES;

    
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.leftNavBtn];
    [self.view addSubview:self.bottomer_heaerView];
    [self.view addSubview:self.bottomer];

}

- (void)setupLayout{
    
    {
        _leftNavBtn.frame = CGRectMake(15, TJ_StatusBarHeight_Define, 44,  44);
    }
    
    {
        _resetPositionIcon.mj_y = _mapView.height - _resetPositionIcon.width - 35;
    }
    
    {
        _bottomer_heaerView.mj_y = _mapView.bottom -20;
    }
    
    {
        _bottomer.mj_y = _bottomer_heaerView.bottom;
    }

}

#pragma mark -

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
    
    if (!animated && !_isFristPositioning ) {
        self.isFristPositioning = YES;
    }
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
    [self.locationManager stopUpdatingLocation];
    
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = userLocation.location.coordinate.latitude;
    coordinate.longitude = userLocation.location.coordinate.longitude;
    [_mapView setCenterCoordinate:coordinate zoomLevel:ZOOM_LEVEL animated:NO];
    
    if (_isUpdateLocation) {
        _isUpdateLocation = NO;
        [self hideProgressView];
        [self setMapRegionWithCoordinate:coordinate];
    }
}


- (void)setMapRegionWithCoordinate:(CLLocationCoordinate2D)coordinate{
    
    MKCoordinateRegion region;
    region = MKCoordinateRegionMake(coordinate, MKCoordinateSpanMake(.01, .01));
    MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:region];
    _isFristPositioning = YES;
    [_mapView setRegion:adjustedRegion animated:YES];
}


//更新用户位置，只要用户改变则调用此方法（包括第一次定位到用户位置）
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated { // 调用获取中心点坐标代理方法
    
    [self.locationManager stopUpdatingLocation];
    
    MKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate2D = mapView.region.center;
    region.center = centerCoordinate2D;
    
    if (self.isFristPositioning && _isChooseUpdateLocation) {
        
        self.isFristPositioning = NO;
        CLLocation *location = [[CLLocation alloc] initWithLatitude:centerCoordinate2D.latitude longitude:centerCoordinate2D.longitude];
        self.useLocation = location;
        
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        
        @weakify(self);
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            @strongify(self);
            CLPlacemark *place = [placemarks firstObject];
            self.fristMapPOI = [[AMapPOI alloc] init];
            NSString *address = [NSString stringWithFormat:@"%@%@%@", [self obtainText:place.locality], [self obtainText:place.subLocality], [self obtainText:place.name]];
            self.fristMapPOI.address = address;
            self.fristMapPOI.location.latitude = place.location.coordinate.latitude;
            self.fristMapPOI.location.longitude = place.location.coordinate.longitude;
            NSLog(@"%@", self.fristMapPOI.address);
            self.bottomer.currentLocationLab.text = self.fristMapPOI.address;
        }];
    }else{
        _isChooseUpdateLocation = YES;
    }
    
    [self bigPinAnimation];
}

- (NSString *)obtainText:(NSString *)text{
    
    return ![JTool iSNull:text] ?text :@"";
}

//大头针跳动的动画
- (void)bigPinAnimation{
    
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        
        CGPoint center = self.bigPin.center;
        center.y -= 20;
        [self.bigPin setCenter:center];
        
    } completion:nil];
    
    [UIView animateWithDuration:0.45 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        
        CGPoint center = self.bigPin.center;
        center.y += 20;
        [self.bigPin setCenter:center];
        
    } completion:nil];
}


- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        MKAnnotationView *annotationView = [[MKAnnotationView alloc]init];
        annotationView.image = [UIImage imageNamed:@"address_map_circle"];
        annotationView.canShowCallout = YES;
        return annotationView;
    }
    return nil;
}

#pragma mark - getter methods

- (UIButton *)leftNavBtn{
    
    if (!_leftNavBtn) {
        _leftNavBtn = [UIButton makeButtonWithImageName:@"nav_back"];
        _leftNavBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        
        kWeakSelf(self);
        _leftNavBtn.tapBlock = ^{
            [weakself.navigationController popViewControllerAnimated:YES];
        };
    }
    
    return _leftNavBtn;
}


//添加地图控件
- (MKMapView *)mapView{
    
    if (!_mapView) {
        
        _mapView = [[MKMapView alloc]initWithFrame:CGRectZero];
        _mapView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight - mBottomerH);

        _mapView.delegate = self;
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        
        if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse){
            [_locationManager requestWhenInUseAuthorization];
        }
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
        
        //大头针
        [_mapView addSubview:self.bigPin];
        [_mapView addSubview:self.greenCircle];

        //重新定位Icon
        [_mapView addSubview:self.resetPositionIcon];
        
    }
    return _mapView;
}


//大头针
- (UIImageView *)bigPin
{
    if (!_bigPin) {
        
        _bigPin = [[UIImageView alloc] init];
        _bigPin.image = [UIImage imageNamed:@"address_bigpin"];
        _bigPin.size = CGSizeMake(20, 40);
        _bigPin.mj_x = KScreenWidth/2.0 - 10;
        _bigPin.mj_y = (KScreenHeight - mBottomerH)/2.0 - 30;
    }
    return _bigPin;
}

- (UIView *)greenCircle{
    
    if (!_greenCircle) {
        _greenCircle = [UIView makeViewBgColor:UIColorFromRGB(0x52C102) cornerRadius:150];
        _greenCircle.alpha = 0.08;
        _greenCircle.size = CGSizeMake(300, 300);
        _greenCircle.mj_x = KScreenWidth/2.0 - 150;
        _greenCircle.mj_y = (KScreenHeight - mBottomerH)/2.0 - 150;
        _greenCircle.userInteractionEnabled = NO;
    }
    return _greenCircle;
}


//重新定位Icon
- (UIButton *)resetPositionIcon
{
    if (!_resetPositionIcon) {
        _resetPositionIcon = [UIButton buttonWithType:UIButtonTypeCustom];
        [_resetPositionIcon setImage:[UIImage imageNamed:@"address_reset"] forState:UIControlStateNormal];
        _resetPositionIcon.size = CGSizeMake(32, 32);
        _resetPositionIcon.contentMode = UIViewContentModeCenter;
        _resetPositionIcon.mj_x = KScreenWidth - _resetPositionIcon.width - 15;
        _resetPositionIcon.isNeedAnimation = YES;
        
        @weakify(self);
        _resetPositionIcon.tapBlock = ^{
            @strongify(self);
            self.isUpdateLocation = YES;
            [self.locationManager startUpdatingLocation];
            [self showProgressView];
        };
    }
    
    return _resetPositionIcon;
}


- (MeaetCityFriendHeader *)bottomer_heaerView{
    
    if (!_bottomer_heaerView) {
        _bottomer_heaerView = [[MeaetCityFriendHeader alloc] init];
        _bottomer_heaerView.titleLab.text = @"标注收货位置，确认是否在冷链配送范围内";
        _bottomer_heaerView.titleLab.textColor = UIColorFromRGB(0x969696);
    }
    return _bottomer_heaerView;
}


- (MeatMapBottomer *)bottomer{
    
    if (!_bottomer) {
        _bottomer = [[MeatMapBottomer alloc] init];
        
        @weakify(self);
        _bottomer.dealResetLocationBlock = ^{
            @strongify(self);
            self.isUpdateLocation = YES;
            [self.locationManager startUpdatingLocation];
            [self showProgressView];
        };
        
        _bottomer.dealInputLocationBlock = ^{
            @strongify(self);
            MeatMapShopAddressViewController *vc = [[MeatMapShopAddressViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        
        _bottomer.dealHistoryLocationBlock = ^(NSInteger params) {
            @strongify(self);

        };

    }
    return _bottomer;
}


@end
